<?php
/*
 * @Date: 2025-04-08 22:08:02
 * @LastEditors: 贾二小 erxiao.jia@outlook.com
 * @LastEditTime: 2025-04-26 13:20:09
 * @FilePath: /admin/app/Http/Controllers/UserController.php
 */

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    public function index()
    {
        $users = User::key(request('key'))
            ->sex(request('sex'))
            ->latest()
            ->paginate(request('per_page', 15));
        return UserResource::collection($users);
    }

    public function store(Request $request, User $user)
    {
        //todo
        Validator::make($request->input(), [
            'email' => ['required', 'unique:users,email'],
        ])->validate();

        $user->fill($request->input() + ['password' => Hash::make($request->input('password'))])->save();
        return $this->success('新增成功', $user);
    }

    public function show(User $user)
    {
        return $this->success(data: new UserResource($user));
    }

    public function update(Request $request, User $user)
    {
        $user->fill($request->input())->save();
        return $this->success('更新成功', $user);
    }

    public function destroy(User $user)
    {
        $user->delete();

        return $this->success(message: '删除成功');
    }
}
